<template>
   <el-dialog title="添加部门" @click="getdept()"  :visible.sync="isShowAddDept" :close-on-click-modal="false">
         <el-form :model="dept" label-width="80px">
     <el-form-item label="部门名称">
        <el-input v-model="dept.name" autocomplete="off"></el-input>
     </el-form-item>
      <el-form-item label="上级部门"  >       
           <el-cascader
           v-model="dept.parentId"
           :options="options"
           :props="{ checkStrictly: true, label:'name',value:'id', children:'children'}"
           clearable>
           </el-cascader>
     </el-form-item>
   <el-form-item label="序号"  >
        <template>
          <el-input-number v-model="dept.orderNum" controls-position="right" :min="1" :max="10"></el-input-number>
       </template>
   </el-form-item>
   </el-form>
   <div slot="footer" class="dialog-footer">
      <el-button @click="()=>isShowAddDept=false">取 消</el-button>
      <el-button type="primary" @click="addDeptShow">确 定</el-button>
   </div>
</el-dialog>
</template>

<script>


export default {
    
     data(){
      return{  
         
          dept:{
            name:'',
            parentId:'',
            orderNum:''
          },
           options:[{
            id:'',
            name:'',
            children:''
       }],  
          isShowAddDept:false,
      }
    } ,      
    methods:{
      getdept(){
           this.$http.get('dept')
           .then(res=>{
            this.options = this.formatData(res.data.data);
           })       
      },
      formatData(data) {
      for (var i = 0; i < data.length; i++) {
        if (data[i].children.length < 1) {
          // children若为空数组，则将children设为undefined
          data[i].children = undefined;
        } else {
          // children若不为空数组，则继续 递归调用 本方法
          this.formatData(data[i].children)
        }
      }
      return data;
    },
  
    async addDeptShow(){ 
        const dept = {
          name: this.dept.name,
          parentId: (this.dept.parentId).length>0?(this.dept.parentId)[this.dept.parentId.length-1]:0,
          orderNum:this.dept.orderNum
        }       
        const r= await this.$http.post('/dept',dept)
         if(r.data.code>0){              
             this.$message({
                 message: '数据添加成功',
                 type: 'success'
                 })
                 // 关闭模态框
                 this.isShowAddDept = false
                 // 数据重新加载
                 this.$emit('refresh')
            }else{
                this.$message({
                 message: '数据添加失败',
                 type: 'success'
                 })
            }
    }
 }
   
   
}
</script>

<style>

</style>